import * as React from 'react';
import styles from './ZhuhuaHt.module.scss';
import { IZhuhuaHtProps } from './IZhuhuaHtProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { Route, HashRouter, Switch, } from 'react-router-dom';
import { Layout, Card, Menu, Tooltip, Icon, Modal, Spin } from 'antd';
import { Link } from "react-router-dom";
import 'antd/dist/antd.css';
import { GetUserRole, GetUserDataPermission } from "./axios/api"
import { dynamicsService }from '../../../services/services'
const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;
import {
  AddContractNo, DeleteNumber, AddContractVersion, SearchCaseFile, SearchRegulationsFile, SearchApplyRegulationsFile, SearchExportContract, SearchExportFile, SearchContract, SearchFile, DocumentLibrary, Dashboard, Regulations, RegulationsVersion, CaseManagement, SearchRegulations, SearchCase, MyTestPage
} from './pages/index';
import LayoutDom from './pages/Layout';
import Api from './config/api';
import { Search } from '@pnp/sp/search';
import { ListGUID } from './config/ListGuid';

export default class DashIndex extends React.Component<IZhuhuaHtProps, any> {
  constructor(props) {
    
 
    super(props)
    this.state = {
      pathname: '', // 当前页面的hash值
      judge: false,
      navLink: [{
        name: '工作台',
        url: '/Dashboard',
        key: 'Dashboard',
        icon: require('../assets/img/gzt.png'),
        aIcon: require('../assets/img/gzt-a.png')
      },{
        name: '文档库',
        url: '/DocumentLibrary',
        key: 'DocumentLibrary',
        icon: require('../assets/img/wdk.png'),
        aIcon: require('../assets/img/wdk-a.png')
      },
      {
        name: '合同申请书文件检索',
        url: '/SearchExportFile',
        key: 'SearchExportFile',
        icon: require('../assets/img/htsqwjjs.png'),
        aIcon: require('../assets/img/htsqwjjs-a.png')
      }, {
        name: '规定申请书文件检索',
        url: '/SearchApplyRegulationsFile',
        key: 'SearchApplyRegulationsFile',
        icon: require('../assets/img/gzzdwjjs.png'),
        aIcon: require('../assets/img/gzzdwjjs-a.png')
      }, {
        name: '全文件检索',
        url: '/SearchFile',
        key: 'SearchFile',
        icon: require('../assets/img/qwjs.png'),
        aIcon: require('../assets/img/qwjs-a.png')
      }],
      isLoading: true
    };
  }
  getConfirmation = (message: any, callback: any) => {
    setTimeout(() => {
      this.setState({
        judge: true
      })
    }, 0)
    Modal.confirm({
      title: message,
      cancelText: '取消',
      okText: '确定',
      onCancel: () => {
        callback(false);
      },
      onOk: () => {
        callback(true);
        this.setState({
          pathname: window.location.hash.slice(1).split('/')[1],
          judge: false
        })

      }
    });
  };
  handleClick = (item) => {
    // setTimeout(()=>{
    //   if(this.state.judge)return;
    //   this.setState({
    //     pathname: item.key,
    //     judge:false
    //   })
    // },0) 
  }
  setRole = (url) => {
    window.open(url)
  }
  //路由跳转
  public async getRoute() {
    window.addEventListener('hashchange', (e) => {
      let pathname = window.location.hash.slice(1).split('/')[1];
      switch (window.location.hash.slice(1).split('/')[1]) {
        case 'AddContractVersion':
          pathname = 'AddContractNo'
          break;
        case 'RegulationsVersion':
          pathname = 'Regulations';
          break;
      }

      this.setState({
        pathname: pathname
      });
    });
  }
  public render(): React.ReactElement<IZhuhuaHtProps> {
    return (
      <div className={styles.z_body}>

        <HashRouter getUserConfirmation={this.getConfirmation}>
          <Layout>
            <Header style={{ background: '#fff', padding: 0 }}>
              <div id="header_div" className={styles.header_div} data-username={this.props.username} data-useremail={this.props.useremail} data-sitelink={this.props.absoluteUrl} data-linkkey="home">
                <div className={styles.header_div_logo}><a href='#/DocumentLibrary'><img src={require("../img/logo.png")}></img></a></div>
                <div className={styles.header_div_h}>
                  <div className={styles.header_div_h_t}>法律文书管理系统</div>
                </div>
                <div className={styles.header_div_logout}>
                  <a href="/sites/legaldoc/_layouts/15/SignOut.aspx">退出</a>
                </div>
              </div>
            </Header>
            <Layout>
              {/* <Sider style={{ background: '#fff' }}>
                <LayoutDom></LayoutDom>
              </Sider> */}
              <Sider
                className='sider-name'
                style={{
                  overflow: 'auto',
                  // height: 'calc(100% - 64px)',
                  width: '220px!important',
                  maxWidth: '220px!important',
                  left: 0,
                  top: 0,
                  bottom: 0,
                  background: '#fff',
                  paddingTop: '25px'
                }}
              >
                {/* {
                  this.state.isLoading ? <div className="loading">
                  <Spin spinning={this.state.isLoading} />
                </div> : null
                } */}


                <Menu mode="inline" className='menu-box' selectedKeys={[this.state.pathname]} onClick={(e) => this.handleClick(e)}>
                  {
                    this.state.navLink.map(item => {
                      return (

                        <Menu.Item key={item.key} className='menu-item'>
                          {
                            item.key !== 'Console' ?
                              <Link to={item.url}>
                                <div>
                                  {this.state.pathname === item.key ? <img src={item.aIcon as string} style={{ marginRight: '15px', marginLeft: '10px', width: '20px' }}></img> : <img style={{ marginRight: '15px', marginLeft: '10px', width: '20px' }} src={item.icon as string}></img>}
                                  <span style={{
                                    width: '70%',
                                    whiteSpace: 'nowrap',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    display: 'block'
                                  }}>{item.name}</span>
                                </div>
                              </Link>
                              :
                              <div className='console' style={{ display: 'flex', alignItems: 'center' }} onClick={() => this.setRole(item.url)}>
                                {this.state.pathname === item.key ? <img src={item.aIcon as string} style={{ marginRight: '15px', marginLeft: '8px', width: '24px', height: '100%' }}></img> : <img style={{ marginRight: '15px', marginLeft: '8px', width: '24px', height: '100%' }} src={item.icon as string}></img>}
                                <span style={{
                                  width: '70%',
                                  whiteSpace: 'nowrap',
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                  display: 'block'
                                }}>{item.name}</span>
                              </div>
                          }


                        </Menu.Item>
                      )
                    })
                  }
                </Menu>
              </Sider>
              {/* height: 'calc(100% - 64px)', */}
              <Content style={{  overflowY: 'scroll', padding: '30px' }}>
                <Card className='main-box' bordered={false}>
                  {
                    !this.state.isLoading ? <Switch>
                      <Route exact={true} path="/" component={DocumentLibrary} />
                      <Route exact={true} path="/Dashboard" component={Dashboard} />
                      <Route exact={true} path="/DocumentLibrary" component={DocumentLibrary} />
                      <Route exact={true} path="/AddContractNo" component={AddContractNo}></Route>
                      <Route exact={true} path="/AddContractVersion" component={AddContractVersion}></Route>
                      <Route exact={true} path="/Regulations" component={Regulations}></Route>
                      <Route exact={true} path="/RegulationsVersion" component={RegulationsVersion}></Route>
                      <Route exact={true} path="/CaseManagement" component={CaseManagement}></Route>
                      <Route exact={true} path="/SearchExportContract" component={SearchExportContract}></Route>
                      <Route exact={true} path="/SearchRegulations" component={SearchRegulations} />
                      <Route exact={true} path="/SearchCase" component={SearchCase}></Route>
                      <Route exact={true} path="/SearchExportFile" component={SearchExportFile}></Route>
                      <Route exact={true} path="/SearchApplyRegulationsFile" component={SearchApplyRegulationsFile}></Route>
                      <Route exact={true} path="/SearchContract" component={SearchContract}></Route>
                      <Route exact={true} path="/SearchRegulationsFile" component={SearchRegulationsFile}></Route>
                      <Route exact={true} path="/SearchCaseFile" component={SearchCaseFile}></Route>
                      <Route exact={true} path="/SearchFile" component={SearchFile}></Route>
                      <Route exact={true} path="/MyTestPage" component={MyTestPage}></Route>
                      <Route exact={true} path="/DeleteNumber" component={DeleteNumber}></Route>
                    </Switch> : <div className="loading">
                      <Spin spinning={this.state.isLoading} />
                    </div>
                  }

                </Card>
              </Content>
            </Layout>
          </Layout>
        </HashRouter>
      </div>
    );
  }
  async componentDidMount() {
    // var p = window.devicePixelRatio;
    // if(p==1.5){
    //     document.body.style.cssText = 'zoom:'+ (-0.6 * p + 1.55) +''
    // }
    // dynamicsService.changeData({ListGUID: '9e17e4f9-4654-4b73-818d-7fb97ce4e5f0'})
    this.getRoute()
    var users = await Api._getUser();
    
    localStorage.setItem('usersList', JSON.stringify(users))

    Api._initAADUsers();//初始化AAD用户
    let user = await Api._getcurrentUser();
    

    let data: any = await GetUserRole({ showtype: 1, email: user.UserPrincipalName.split('@')[0] });
    sessionStorage.setItem('userInfo', JSON.stringify(user))
    if (data.data && data.data.length > 0) {
      data.data.forEach(item => {
        item.funcName = item.funcName.split(',').map(i => item.funcPagePath + '/' + i)
      });
      let funPath = data.data.map(item => item.funcName).flat(1);
      sessionStorage.setItem('userRole', JSON.stringify(funPath));
      sessionStorage.setItem('userRoleName', JSON.stringify(data.data[0].roleName));
      const navLinkGroups = [
        {
          name: '工作台',
          url: '/Dashboard',
          key: 'Dashboard',
          icon: require('../assets/img/gzt.png'),
          aIcon: require('../assets/img/gzt-a.png')
        }, {
          name: '文档库',
          url: '/DocumentLibrary',
          key: 'DocumentLibrary',
          icon: require('../assets/img/wdk.png'),
          aIcon: require('../assets/img/wdk-a.png')
        }, {
          name: '合同编号',
          url: '/AddContractNo',
          key: 'AddContractNo',
          icon: require('../assets/img/xht.png'),
          aIcon: require('../assets/img/xht-a.png')
        },
        {
          name: '合同编号检索导出',
          url: '/SearchExportContract',
          key: 'SearchExportContract',
          icon: require('../assets/img/htjs.png'),
          aIcon: require('../assets/img/htjs-a.png')
        },
        {
          name: '合同台账文件检索',
          url: '/SearchContract',
          key: 'SearchContract',
          icon: require('../assets/img/htwjjs.png'),
          aIcon: require('../assets/img/htwjjs-a.png')
        },
        {
          name: '合同申请书文件检索',
          url: '/SearchExportFile',
          key: 'SearchExportFile',
          icon: require('../assets/img/htsqwjjs.png'),
          aIcon: require('../assets/img/htsqwjjs-a.png')
        },
        // {
        //   name: '新合同版本号',
        //   url: '/AddContractVersion',
        //   key: 'AddContractVersion',
        //   icon: require('../assets/img/xhtbbh.png'),
        //   aIcon: require('../assets/img/xhtbbh-a.png')
        // },
        {
          name: '规章制度编号',
          url: '/Regulations',
          key: 'Regulations',
          icon: require('../assets/img/gzzd.png'),
          aIcon: require('../assets/img/gzzd-a.png')
        },
        {
          name: '规定编号检索导出',
          url: '/SearchRegulations',
          key: 'SearchRegulations',
          icon: require('../assets/img/gzzdjs.png'),
          aIcon: require('../assets/img/gzzdjs-a.png')
        },
        {
          name: '规定台账文件检索',
          url: '/SearchRegulationsFile',
          key: 'SearchRegulationsFile',
          icon: require('../assets/img/gzzdwjjs.png'),
          aIcon: require('../assets/img/gzzdwjjs-a.png')
        },
        {
          name: '规定申请书文件检索',
          url: '/SearchApplyRegulationsFile',
          key: 'SearchApplyRegulationsFile',
          icon: require('../assets/img/gdsqsjs.png'),
          aIcon: require('../assets/img/gdsqsjs-a.png')
        },
        // {
        //   name: '规章制度版本号',
        //   url: '/RegulationsVersion',
        //   key: 'RegulationsVersion',
        //   icon: require('../assets/img/gzzdbbh.png'),
        //   aIcon: require('../assets/img/gzzdbbh-a.png')
        // }, 
        {
          name: '案件编号',
          url: '/CaseManagement',
          key: 'CaseManagement',
          icon: require('../assets/img/ajgl.png'),
          aIcon: require('../assets/img/ajgl-a.png')
        },
        {
          name: '案件编号检索导出',
          url: '/SearchCase',
          key: 'SearchCase',
          icon: require('../assets/img/ajgljs.png'),
          aIcon: require('../assets/img/ajgljs-a.png')
        },
        {
          name: '案件文件检索',
          url: '/SearchCaseFile',
          key: 'SearchCaseFile',
          icon: require('../assets/img/ajwjjs.png'),
          aIcon: require('../assets/img/ajwjjs-a.png')
        },
        {
          name: '全文件检索',
          url: '/SearchFile',
          key: 'SearchFile',
          icon: require('../assets/img/qwjs.png'),
          aIcon: require('../assets/img/qwjs-a.png')
        },{
          name: '台账删除编号',
          url: '/DeleteNumber',
          key: 'DeleteNumber',
          icon: require('../assets/img/scbh.png'),
          aIcon: require('../assets/img/scbh-a.png')
        },
      ];
      let navLinkArr = [];
      navLinkGroups.forEach(i => {
        if (funPath.includes(i.key + '/' + 'disp')) {
          navLinkArr.push(i)
        }
      })
      let pathname = sessionStorage.getItem('userRole') && window.location.hash.slice(1).split('/')[1] ? window.location.hash.slice(1).split('/')[1] : 'DocumentLibrary';
      switch (window.location.hash.slice(1).split('/')[1]) {
        case 'AddContractVersion':
          pathname = 'AddContractNo'
          break;
        case 'RegulationsVersion':
          pathname = 'Regulations';
          break;
      }
      this.setState({
        navLink: navLinkArr,
        pathname: pathname,
        isLoading: false
      })
    } else {
      sessionStorage.setItem('userRole', JSON.stringify([]));
      this.setState({
        pathname: window.location.hash.slice(1).split('/')[1] ? window.location.hash.slice(1).split('/')[1] : 'DocumentLibrary',
        isLoading: false
      })
    }
    let userDataPermission: any = await GetUserDataPermission({ email: user.UserPrincipalName.split('@')[0] })
    sessionStorage.setItem('userDataPermissions', JSON.stringify(userDataPermission.data))
    let userDataPer = await dynamicsService.GetUserPer({ email: user.UserPrincipalName })
    sessionStorage.setItem('userDataPer', JSON.stringify(userDataPer.data))
    if (!window.location.hash.slice(1).split('/')[1]) {
      location.href = window.location.href.split('#')[0] + '#/DocumentLibrary'
    }
  }
}
